package org.example.system.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import org.example.system.common.result.Result;
import org.example.system.model.dto.FileInfo;
import org.example.system.model.dto.RealNameAuthRequest;
import org.example.system.model.entity.Tenant;
import org.example.system.model.form.TenantForm;
import org.example.system.model.query.TenantPageQuery;
import org.example.system.model.vo.PageVo;
import org.example.system.service.BaiduAiService;
import org.example.system.service.OssService;
import org.example.system.service.TenantService;
import org.modelmapper.ModelMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Tag(name = "09.租户管理")
@RestController
@RequestMapping("/api/v1/tenant")
@Slf4j
public class TenantController {

    @Resource
    private TenantService tenantService;

    @Resource
    private ModelMapper modelMapper;

    @Resource(name = "aliYunOssService")
    private OssService ossService;

    @Resource
    private BaiduAiService baiduAiService;


    @Operation(summary = "多条件分页查询租客信息")
    @PostMapping("/search")
    public Result queryTenantByPage(@RequestBody TenantPageQuery tenantPageQuery) {
        LambdaQueryWrapper<Tenant> criteria = new LambdaQueryWrapper<>();
        if(StringUtils.hasLength(tenantPageQuery.getKeyword())) {
            /*criteria.like(Tenant::getName, tenantPageQuery.getKeyword())
                    .or()
                    .like(Tenant::getPhone, tenantPageQuery.getKeyword())
                    .or()
                    .like(Tenant::getNickName, tenantPageQuery.getKeyword());*/

            criteria.like(Tenant::getName, tenantPageQuery.getKeyword())
                    .or(k-> k.like(Tenant::getPhone, tenantPageQuery.getKeyword()))
                    .or(f -> f.like(Tenant::getNickName, tenantPageQuery.getKeyword()));
        }
        if(tenantPageQuery.getStatus() != null && tenantPageQuery.getStatus() != -1) {
            criteria.eq(Tenant::getStatus, tenantPageQuery.getStatus());
        }
        int pageNum = tenantPageQuery.getPageNum();
        int pageSize = tenantPageQuery.getPageSize();
        Page<Tenant> page = new Page<>(pageNum, pageSize);
        Page<Tenant> tenantPage = tenantService.page(page, criteria);
        PageVo pageVo = new PageVo();
        pageVo.setTotal(tenantPage.getTotal());
        pageVo.setList(tenantPage.getRecords());
        return Result.success(pageVo);
    }

    @Operation(summary = "销户")
    @DeleteMapping("/delete/{id}")
    public Result deleteByID(@PathVariable Integer id) {
        tenantService.xiaohu(id);
        return Result.success();
    }

    @Operation(summary = "修改租户信息/上传租户信息")
    @PutMapping("/update")
    public Result updateById(@RequestBody TenantForm tenantFrom) {
        // 将TenantFrom转换为Tenant
        Tenant tenant = modelMapper.map(tenantFrom, Tenant.class);
        // 检查身份证号是否已存在
        LambdaQueryWrapper<Tenant> criteria = new LambdaQueryWrapper<>();
        criteria.eq(Tenant::getIdNo, tenant.getIdNo());
        // 如果不是修改自己的信息，则检查身份证号是否已存在
        if (tenantService.count(criteria) > 0) {
            return Result.failed("身份证号已存在");
        }
        // 检查手机号是否已存在
        if(tenantFrom.getPhone() != null){
            int phonsSize = tenantFrom.getPhone().length();
            // 判断手机号是否为11位
            if(phonsSize != 11){
                return Result.failed("手机号格式不正确");
            }
        }
        // 判断头像上传是否为空 如果不是空 则执行
        if(tenantFrom.getAvatarFile() != null){
            // 将头像文件上传到OSS
            // 将上传后的文件信息保存到tenant对象中
            FileInfo avatarFile = ossService.uploadFile(tenantFrom.getAvatarFile());
            tenant.setAvatarUrl(avatarFile.getUrl());
        }
        // 判断驾驶证上传是否为空 如果不是空 则执行
        if(tenantFrom.getDrivingCertFile() != null){
            // 将驾驶证文件上传到OSS
            // 将上传后的文件信息保存到tenant对象中
        FileInfo driveFile = ossService.uploadFile(tenantFrom.getDrivingCertFile());
        tenant.setDrivingCert(driveFile.getUrl());
        }
        // 更新租户信息
        tenantService.updateById(tenant);
        return Result.success();
    }

    @Operation(summary = "删除头像文件")
    @GetMapping("/delete/avatar/file")
    public Result deleteAvatarFile(String avatarName) throws Exception {
        ossService.deleteFile(avatarName);
        return Result.success();
    }

    @Operation(summary = "删除驾驶证文件")
    @GetMapping("/delete/drive/file")
    public Result deleteDriveFile(String driveName) throws Exception {
        ossService.deleteFile(driveName);
        return Result.success();
    }
    @Operation(summary = "获取租户详情")
    @GetMapping("/detail/{id}")
    public Result selectTenantById(@PathVariable(name = "id") Integer id) {
        LambdaQueryWrapper<Tenant> criteria = new LambdaQueryWrapper<>();
        criteria.eq(Tenant::getId, id);
        Optional<Tenant> tenantOpt = tenantService.getOneOpt(criteria);
        if(tenantOpt.isPresent()){
            Tenant tenant = tenantOpt.get();
            return Result.success(tenant);
        }
        return Result.failed("租户ID不存在");
    }

    @Operation(summary = "封号")
    @DeleteMapping("/remove/{id}")
    public Result forbidById(@PathVariable Integer id) {
        tenantService.removeById(id);
        return Result.success();
    }

    @Operation(summary = "解封")
    @PutMapping("/release/{id}")
    public Result releaseById(@PathVariable Integer id) {
        tenantService.jiefeng(id);
        return Result.success();
    }

    @Operation(summary = "更改用户状态")
    // 路径参数
    @PutMapping("/update/status/{id}/{status}")
    public Result updateStatusById(@PathVariable Integer id , @PathVariable Integer status) {
        Tenant tenant = new Tenant();
        tenant.setId(id);
        if (status == -1){
            tenant.setStatus(2);
            tenantService.updateById(tenant);

        } else if (status == 1){
            tenant.setStatus(1);
            tenantService.updateById(tenant);
        }
        return Result.success();
    }

    @Operation(summary = "根据身份证正反面图片和OpenID更新租户信息")
    @PostMapping("/update/idCard")
    public Result updateTenantIdCard(
            @RequestParam String openid,
            @RequestParam String frontFile,
            @RequestParam String backFile) {
        // 查询是否存在对应的租户
        LambdaQueryWrapper<Tenant> criteria = new LambdaQueryWrapper<>();
        criteria.eq(Tenant::getOpenId, openid);
        Tenant tenant = tenantService.getOne(criteria);

        if (tenant == null) {
            return Result.failed("未找到与该OpenID对应的租户信息");
        }

        // 更新身份证正面和反面图片URL
        tenant.setIdCardFrontPath(frontFile);
        tenant.setIdCardBackPath(backFile);

        // 执行更新操作
        boolean isUpdated = tenantService.updateById(tenant);
        if (isUpdated) {
            return Result.success("租户信息更新成功");
        }

        return Result.failed("租户信息更新失败");
    }



    @PostMapping("/realNameAuthentication")
    @Operation(summary = "实名认证接口")
    public Result realNameAuthentication(@RequestBody RealNameAuthRequest request) {
        String openid = request.getOpenid();
        String name = request.getName();
        String idCard = request.getIdCard();
        String frontFileUrl = request.getFrontFile();
        String backFileUrl = request.getBackFile();

        // 查询租户信息
        LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Tenant::getOpenId, openid);
        Tenant tenant = tenantService.getOne(queryWrapper);

        if (tenant == null) {
            return Result.failed("未找到对应的租户信息");
        }

        try {
            // 调用身份证信息提取验证服务
            String extractedResult;
            try {
                extractedResult = baiduAiService.validateIdCard(frontFileUrl, backFileUrl);
            } catch (Exception e) {
                e.printStackTrace();
                tenant.setStatus(2);
                tenantService.updateById(tenant);
                return Result.failed("身份证信息提取失败: " + e.getMessage());
            }

            // 校验提取的身份证信息与表单信息是否匹配
            if (!extractedResult.contains(name) || !extractedResult.contains(idCard)) {
                tenant.setStatus(2);
                tenantService.updateById(tenant);
                return Result.failed("身份证信息与表单信息不一致");
            }

            // 更新租户身份证信息
            tenant.setIdCardFrontPath(frontFileUrl);
            tenant.setIdCardBackPath(backFileUrl);
            tenant.setIdNo(idCard);
            tenant.setName(name);

            tenantService.updateById(tenant);

            if (tenant.getStatus() == 0 ){
                tenant.setStatus(1);
            }
            if(tenant.getStatus() == 2){
                tenant.setStatus(3);
            }

            tenantService.updateById(tenant);

            return Result.success("实名认证成功");
        } catch (Exception e) {
            tenant.setStatus(2);
            tenantService.updateById(tenant);
            e.printStackTrace();
            return Result.failed("实名认证失败: " + e.getMessage());
        }
    }


    @PostMapping("/validate-license")
    @Operation(summary = "驾驶证验证")
    public Result<String> validateDrivingLicense(
            @RequestParam String openid,
            @Parameter(description = "驾驶证文件") @RequestParam("file") String file
    ) throws Exception {

        // 更新租户信息
        LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Tenant::getOpenId, openid);
        Tenant tenant = tenantService.getOne(queryWrapper);

        // 调用驾驶证识别服务
        String result;
        try {
            result = baiduAiService.drivingLicenseRecognition(file);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("驾驶证验证失败: " + e.getMessage());
        }

        tenant.setDrivingCert(file);
        if (tenant.getStatus() == 0){
            tenant.setStatus(2);
        }
        if(tenant.getStatus() == 1){
            tenant.setStatus(3);
        }

        tenantService.updateById(tenant);

        return Result.success(result);
    }


}